package map_;

import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author DCSGO
 * @version 1.0
 */

@SuppressWarnings({"all"})
public class TreeMap_ {
    //与 TreeSet 相似通过无参构造器 创建 TreeMap 也是无序的
    //非基础数据类型(String除外)甚至都不能直接添加 必须指定比较器
    public static void main(String[] args) {
/*
        TreeMap treeMap = new TreeMap();
        treeMap.put(new int[]{1,2,3},1);
        treeMap.put(new Car("宝马",1111),1);
        treeMap.put(new Car("奔驰",1221),1);
        treeMap.put(new Car("红旗",3111),1);
*/
        //报错：ClassCastException: [I cannot be cast to java.lang.Comparable

        //根据车名和价格进行降序排序
        TreeMap treeMap1 = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Car car1 = (Car) o1;
                Car car2 = (Car) o2;
                if (car1.getName().equals(car2.getName())) {
                    return car1.getPrice() - car2.getPrice();
                } else {
                    return car2.getName().compareTo(car1.getName());
                }
            }
        });
        treeMap1.put(new Car("bao", 1111), 1);
        treeMap1.put(new Car("ben", 1221), 1);
        treeMap1.put(new Car("niu", 3111), 1);
        treeMap1.put(new Car("niu", 211), 1);

        Set keySet = treeMap1.keySet();
        for (Object car : keySet) {
            System.out.println(car + " " + treeMap1.get(car));
        }
        //Car{name='niu', price=211} 1
        //Car{name='niu', price=3111} 1
        //Car{name='ben', price=1221} 1
        //Car{name='bao', price=1111} 1
    }
}

class Car {
    private String name;
    private int price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public Car(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
